package ui;

import javax.swing.*;
import java.awt.*;
import java.sql.*;
import util.ConnectionUtils;

public class AppointmentDialog extends JDialog {
    private String patientId;
    private DefaultListModel<String> doctorListModel;
    private JList<String> doctorList;
    private JComboBox<String> departmentBox;

    public AppointmentDialog(JFrame parent, String patientId) {
        super(parent, "预约挂号", true);
        this.patientId = patientId;
        
        setSize(500, 400);
        setLocationRelativeTo(parent);
        setLayout(new BorderLayout(10, 10));
        
        // 创建科室选择面板
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        departmentBox = new JComboBox<>(new String[]{"内科", "外科", "儿科"});
        topPanel.add(new JLabel("选择科室："));
        topPanel.add(departmentBox);
        add(topPanel, BorderLayout.NORTH);
        
        // 创建医生列表
        doctorListModel = new DefaultListModel<>();
        doctorList = new JList<>(doctorListModel);
        doctorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(new JScrollPane(doctorList), BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton appointButton = new JButton("预约");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(appointButton);
        buttonPanel.add(cancelButton);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加科室选择事件
        departmentBox.addActionListener(e -> updateDoctorList());
        
        // 添加预约按钮事件
        appointButton.addActionListener(e -> {
            if (doctorList.getSelectedValue() != null) {
                makeAppointment(doctorList.getSelectedValue().split(" ")[0]); // 获取医生ID
            } else {
                JOptionPane.showMessageDialog(this, "请选择一位医生");
            }
        });
        
        // 添加取消按钮事件
        cancelButton.addActionListener(e -> dispose());
        
        // 初始加载医生列表
        updateDoctorList();
    }
    
    private void updateDoctorList() {
        doctorListModel.clear();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = ConnectionUtils.getConn();
            String sql = "SELECT d.id, u.name, d.doctorRank FROM doctor d " +
                        "JOIN user u ON d.user_id = u.id " +
                        "WHERE d.department = ? AND d.status = 1";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, (String) departmentBox.getSelectedItem());
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                String doctorInfo = String.format("%s - %s (%s)", 
                    rs.getString("id"),
                    rs.getString("name"),
                    rs.getString("doctorRank"));
                doctorListModel.addElement(doctorInfo);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "获取医生列表失败：" + ex.getMessage());
        } finally {
            ConnectionUtils.close(conn, pstmt, rs);
        }
    }
    
    private void makeAppointment(String doctorId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = ConnectionUtils.getConn();
            String appointmentId = "APT" + System.currentTimeMillis();
            String sql = "INSERT INTO appointment (id, patient_id, doctor_id, appointment_time, status, create_time) " +
                        "VALUES (?, ?, ?, ?, 0, NOW())";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, appointmentId);
            pstmt.setString(2, patientId);
            pstmt.setString(3, doctorId);
            pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis() + 24*60*60*1000)); // 明天
            
            int result = pstmt.executeUpdate();
            if (result > 0) {
                JOptionPane.showMessageDialog(this, "预约成功！预约号：" + appointmentId);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "预约失败，请稍后重试");
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "预约失败：" + ex.getMessage());
        } finally {
            ConnectionUtils.close(conn, pstmt, null);
        }
    }
} 